package com.yd.mvc.baseController.interceptor;

import com.yd.app.util.BusinessException;
import com.yd.mvc.baseController.util.AuthUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 登陆拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
	protected static final Logger LOGGER = LoggerFactory.getLogger(HandlerInterceptor.class);

	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
//		String header=request.getHeader("X-Requested-With");
//		boolean isAjax="XMLHttpRequest".equals(header);
		HandlerMethod method = (HandlerMethod) handler;
		if (AuthUtil.auth(request, response)) {
			//根据QltAuth注解 验证权限
			//checkRights(method);
			//将当前登录用户信息放入request中
			Map<String,String> user=new HashMap<String, String>(){{
				put("id", AuthUtil.getCurrentUser().getUserId());
				put("name",AuthUtil.getCurrentUser().getUserName());
			}};
			request.setAttribute("cu", user);
			return true;
		} else {
			request.removeAttribute("cu");

			throw new BusinessException(401,"您尚未登录，请登录后重试","no-login");
		}
	}

	public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {

	}

	public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception {
		AuthUtil.leave();
	}


}